﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HuoTu.Common
{
    /// <summary>
    /// 枚举数据处理
    /// </summary>
    public class SysEnum
    {
        /// <summary>
        /// 获取枚举的注释
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetEnumDescription<T>(int value) where T : new()
        {
            Type t = typeof(T);
            foreach (System.Reflection.MemberInfo mInfo in t.GetMembers())
            {
                if (mInfo.Name == t.GetEnumName(value))
                {
                    foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo))
                    {
                        if (attr.GetType() == typeof(System.ComponentModel.DescriptionAttribute))
                        {
                            return ((System.ComponentModel.DescriptionAttribute)attr).Description;
                        }
                    }
                }
            }
            return "";
        }

        public static bool Contains<T>(int value)
        {
            bool val = false;
            Type t = typeof(T);
            foreach (System.Reflection.MemberInfo mInfo in t.GetMembers())
            {
                if (mInfo.Name == t.GetEnumName(value))
                {
                    val = true;
                    break;
                }
            }
            return val;
        }



        public static List<EnumModel> Enum2List<T>() where T : new()
        {
            List<EnumModel> result = new List<EnumModel>();
            Type t = typeof(T);
            foreach (var n in t.GetEnumValues()) //Enum.GetValues();
            {
                int value = (int)n;
                result.Add(new EnumModel()
                {
                    Value = value,
                    Description = GetEnumDescription<T>(value)
                });
            }
            return result;

        }
    }

    public class EnumModel
    {
        public int Value { get; set; }
        public string Description { get; set; }
    }
}
